package _8_Gorm框架老郭

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

// 创建记录
func createDB() {
	type User struct {
		gorm.Model
		Name     string
		Age      uint
		Birthday time.Time
	}

	dsn := "root:123456@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect darabase")
	}
	user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}

	db.AutoMigrate(&User{})    //创建表
	result := db.Create(&user) // 通过数据的指针来创建记录/数据

	fmt.Printf("user.ID:%v\n", user.ID)                         // 返回插入数据的主键
	fmt.Printf("result.Error:%v\n", result.Error)               // 返回 error
	fmt.Printf("result.RowsAffected:%v\n", result.RowsAffected) // 返回插入记录的条数

	//(1)创建指定的字段
	db.Select("Name", "Age", "CreatedAt").Create(&user)
	// INSERT INTO `users` (`name`,`age`,`created_at`) VALUES ("jinzhu", 18, "2020-07-04 11:05:21.775")

	//(2)创建指定字段以外的字段的值
	db.Omit("Name", "Age", "CreatedAt").Create(&user)
	// INSERT INTO `users` (`birthday`,`updated_at`) VALUES ("2020-01-01 00:00:00.000", "2020-07-04 11:05:21.775")

	//(3)批量插入
	var users = []User{{Name: "jinzhu1"}, {Name: "jinzhu2"}, {Name: "jinzhu3"}}
	db.Create(&users)

	for _, user := range users {
		fmt.Printf("user.ID:%v\n", user.ID) // 返回插入数据的主键 1,2,3
	}

	//(4)使用 CreateInBatches 分批创建时，你可以指定每批的数量
	var usera = []User{{Name: "jinzhu_1"}, {Name: "jinzhu2"}, {Name: "jinzhu_10000"}}

	// 数量为 100
	db.CreateInBatches(usera, 100)
}

// 创建钩子Hook
// GORM 允许用户定义的钩子有 BeforeSave, BeforeCreate, AfterSave, AfterCreate 创建记录时将调用这些钩子方法
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	/*u.UUID = uuid.New()

	if u.Role == "admin" {
		return errors.New("invalid role")
	}*/
	//创建数据之前调用Hook
	return
}

// 根据 Map 创建
// 支持根据 map[string]interface{} 和 []map[string]interface{}{} 创建记录
func createMap() {
	dsn := "root:123456@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect darabase")
	}

	db.Model(&User{}).Create(map[string]interface{}{
		"Name": "jinzhu", "Age": 18,
	})

	// batch insert from `[]map[string]interface{}{}`
	db.Model(&User{}).Create([]map[string]interface{}{
		{"Name": "jinzhu_1", "Age": 18},
		{"Name": "jinzhu_2", "Age": 20},
	})
}
